package training.framework.presentation;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import training.framework.business.AbstractEntity;
import training.framework.business.AbstractEntityController;
import training.framework.business.AbstractEntitySearchOptions;


public abstract class AbstractEditEntity<Identifier, 
						Entity extends AbstractEntity<Identifier>, 
						EntitySearchOptions extends AbstractEntitySearchOptions, 
						EntityPanel extends AbstractEntityPanel<Identifier, Entity>> {
	
	private EntityPanel panel;
	private boolean entitySaved;
	private Class<EntityPanel> entityPanelClass;
	private String savedMessage;
	private String initializeOutCome;
	
	public AbstractEditEntity(Class<EntityPanel> entityPanelClass, String initializeOutCome, String savedMessage) {
		
		if(entityPanelClass == null){
			throw new IllegalArgumentException("entityPanelClass == null");
		}
		
		if(initializeOutCome == null){
			throw new IllegalArgumentException("initializeOutCome == null");
		}
		
		if(savedMessage == null){
			throw new IllegalArgumentException("savedMessage == null");
		}
		
		this.entityPanelClass = entityPanelClass;
		this.initializeOutCome = initializeOutCome;
		this.savedMessage = savedMessage;
	}

	public AbstractEditEntity() {}
		
	@SuppressWarnings("unchecked")
	public String initialize(Entity entity) throws InstantiationException, IllegalAccessException {
		entity = (Entity) entity.clone();
		panel = entityPanelClass.newInstance();
		panel.setEntity(entity);
		entitySaved = false;
		return initializeOutCome;
	}
	
	public EntityPanel getPanel() {
		return panel;
	}

	public boolean getEntitySaved() {
		return entitySaved;
	}	
	
	public void saveEntity() {
		FacesMessage message = new FacesMessage();

		AbstractEntityController<Identifier, Entity, EntitySearchOptions> controller = getController();
		controller.saveEntity(panel.getEntity());
		
		entitySaved = true;
		message.setSummary(savedMessage);
		message.setSeverity(FacesMessage.SEVERITY_INFO);
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, message);					
	}
	
	protected abstract AbstractEntityController<Identifier, Entity, EntitySearchOptions> getController();

}